package com.thread.thread.CompletableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.function.Supplier;

/*
* 注意：带async的都新开线程执行，不带 的都会阻塞
*/
public class CompletableFutureTest {
	static ExecutorService executorService= Executors.newFixedThreadPool(5);
	public static void main(String[] args) throws  Exception{
		System.out.println("序号1"+Thread.currentThread().getName());
		CompletableFuture<Void> voidableFuture=CompletableFuture.runAsync(new Runnable() {
			@Override
			public void run() {

				System.out.println("序号2"+"无返回值runAsync"+Thread.currentThread().getName());
			}
		}, executorService);

		CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {

			System.out.println("序号3"+Thread.currentThread().getName());

			return "有返回值supplyAsync";
		}, executorService);
		/*计算结果完成时回调*/

		//交给当前主线程继续执行(该方法会阻塞当前线程)
		future.whenComplete((x,y)-> {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("序号4"+x+","+y+","+Thread.currentThread().getName());
			throw  new NullPointerException();
		}).exceptionally(
				throwable -> {
					System.out.println("序号12"+throwable.toString());
					return "发生异常";
				}
		);

		//交给线程池新起线程执行
		voidableFuture.whenCompleteAsync((x,y)-> System.out.println("序号5"+x+","+y+","+Thread.currentThread().getName()),executorService);

		/*第二个线程依赖第一个的结果*/
		//thenApply,一个线程依赖另一个线程可以使用,出现异常不执行,会阻塞，用的为main线程

		CompletableFuture<Integer> future2=CompletableFuture.supplyAsync(()->1).thenApply((x)->{
			System.out.println("序号6"+x+Thread.currentThread().getName());
		/*	try {
				throw  new NullPointerException("1");
			} catch (NullPointerException e) {
				e.printStackTrace();
			}*/
			return x+1;
		});

		//handle 是执行任务完成时对结果的处理,第一个出现异常继续执行
		CompletableFuture<Integer> future3=future2.handleAsync((x,y)->{
			System.out.println("序号7"+x+","+y+","+Thread.currentThread().getName());
				return 1;
		});

		//thenAccept 消费处理结果,不返回,会阻塞
		future3.thenAccept(x->{
			System.out.println("序号8,"+x+","+Thread.currentThread().getName());
		});
		//thenRun 不关心处理结果，不返回，
		future3.thenRunAsync(()->{
			System.out.println("序号9，"+Thread.currentThread().getName());
		});
		//thenCombine 合并两个线程的执行结果
		CompletableFuture<Integer> future4=future2.thenCombine(future3,(x,y)->{
			System.out.println("序号10，"+x+","+y+","+Thread.currentThread().getName());
			return x+y;
		});

		//runAfterEither 哪个CompletionStagestage执行的快 获取谁的结果

		future3.runAfterEither(future2,()->{
			System.out.println("序号11有人完成了，我就要执行"+Thread.currentThread().getName());
		});


		//runAfterBoth 都执行完成才会继续执行
		future3.runAfterBoth(future2,()->{
			System.out.println("序号12都完成了，我就要执行"+Thread.currentThread().getName());
		});
		System.out.println("序号13"+111);


	}


}
